import axios from "axios";
import { ElMessage } from 'element-plus'
import { getLocaleStorage } from '@/utils/index.ts'
const instance = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 30000,
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    }
})

// 请求拦截器
instance.interceptors.request.use(config => {
    const token = getLocaleStorage('token')
    if (token) {
        config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
}, error => {
    return Promise.reject(error);
})

// 响应拦截器
instance.interceptors.response.use(res => {
    if (res.data.success) {
        return res
    } else {
        ElMessage.error(res.data.message)
        return Promise.reject(res.data.message)
    }

}, error => {
    if (error.response) {
        switch (error.response.status) {
            case 401:
                ElMessage.error('未授权，请重新登录')
                break
            case 403:
                ElMessage.error('拒绝访问')
                break
            case 404:
                ElMessage.error('请求错误，未找到该资源')
                break
            case 500:
                ElMessage.error('服务器出错了')
                break
            default:
                ElMessage.error(`连接错误${error.response.status}`)
                break
        }
    } else {
        ElMessage.error('连接服务器失败')
    }
    return Promise.reject(error)
})

export default instance